package combine.backend.view.action.order;

import java.util.ArrayList;
import java.util.List;

import combine.backend.view.action.BaseAction;
import combine.order.model.BOMItem;
import combine.order.model.BOMItemExtra;
import combine.order.model.DataBase;
import combine.order.model.MaterialProduct;
import combine.order.model.MaterialProductBase;
import combine.order.model.Order;
import combine.order.model.OrderItem;
import combine.order.model.PurchaseOrder;
import combine.order.model.PurchaseOrderItem;

@SuppressWarnings("serial")
public class OrderAction extends BaseAction {

	long orderId;

	long bomId;

	OrderItem item;

	List<Order> orders;

	List<BOMItem> bomItems;

	BOMItem bomItem;

	List<OrderItem> orderItems;

	BOMItemExtra extra;

	List<PurchaseOrder> purchaseOrders;

	long purchaseOrderId;

	List<PurchaseOrderItem> purchaseOrderItems;

	long purchaseOrderItemId;

	int recommendOrderNumber;

	boolean canGetMaterial;

	public String addOrder() {
		try {
			orderId = orderManger.insertOrder(orderId, item);
		} catch (Exception e) {
			setError();
			e.printStackTrace();
			return ERROR;
		}
		setOK();
		return SUCCESS;
	}

	public String findUnFinishOrder() {
		try {
			orders = orderManger.findUnFinishOrder();
			totalCount = orders.size();
		} catch (Exception e) {
			setError();
			e.printStackTrace();
			return ERROR;
		}
		setOK();
		return SUCCESS;
	}

	public String findBOMProductsByOrderId() {
		try {
			bomItems = bomManager.findBomItemsByOrderId(orderId);
			if (bomItems.size() != 0) {
				setOK();
				return SUCCESS;
			}
			Order order = orderManger.findOrderByOrderId(orderId);
			if (order == null) {
				setError();
				return ERROR;
			}
			List<OrderItem> items = order.getItem();
			for (OrderItem item : items) {
				long colorId = item.getOrderColorId();
				int sNumber = item.getSNumber();
				int mNumber = item.getMNumber();
				int lNumber = item.getLNumber();
				int xlNumber = item.getXlNumber();
				int totalNumber = item.getTotalNumber();

				for (MaterialProduct product : DataBase.products) {
					if (product.getProductLengthId() == 0
							&& product.getProductColorId() == colorId) {
						addBOMItem(bomItems, product, orderId, totalNumber);
						continue;
					}
					if (product.getProductLengthId() > 0
							&& product.getProductColorId() > 0
							&& product.getProductColorId() == colorId) {
						if (sNumber != 0
								&& product.getProductLengthId() == DataBase.productLengths
										.get(0).getProductLengthId()) {
							addBOMItem(bomItems, product, orderId, sNumber);
							continue;
						}
						if (mNumber != 0
								&& product.getProductLengthId() == DataBase.productLengths
										.get(1).getProductLengthId()) {
							addBOMItem(bomItems, product, orderId, mNumber);
							continue;
						}
						if (lNumber != 0
								&& product.getProductLengthId() == DataBase.productLengths
										.get(2).getProductLengthId()) {
							addBOMItem(bomItems, product, orderId, lNumber);
							continue;
						}
						if (xlNumber != 0
								&& product.getProductLengthId() == DataBase.productLengths
										.get(3).getProductLengthId()) {
							addBOMItem(bomItems, product, orderId, xlNumber);
							continue;
						}
					}
				}
			}
			print(bomItems);
			order.setIsBom(true);
		} catch (Exception e) {
			setError();
			e.printStackTrace();
		}
		setOK();
		return SUCCESS;
	}

	public String findBomByBomId() {
		bomItem = bomManager.findBomItemById(bomId);
		setOK();
		return SUCCESS;
	}

	public String findOrderItemsByOrderId() {
		try {
			orderItems = orderManger.findItemsByOrderId(orderId);
		} catch (Exception e) {
			setError();
			e.printStackTrace();
			return ERROR;
		}
		setOK();
		return SUCCESS;
	}

	private void print(List<BOMItem> bomItems) {
		System.out.println("-------------");
		System.out.println(bomItems.size());
		for (BOMItem mItem : bomItems) {
			MaterialProduct mProdcut = mItem.getProduct();
			MaterialProductBase base = mProdcut.getBaseProduct();
			System.out.println(base.getBaseProductName()
					+ "-"
					+ mProdcut.getProductColor().getProductColorName()
					+ "-"
					+ (mProdcut.getProductLength() != null ? mProdcut
							.getProductLength().getProductLengthShow() : "")
					+ ":" + mItem.getOrderNumber());
		}
	}

	private BOMItem addBOMItem(List<BOMItem> items, MaterialProduct product,
			long orderId, int number) throws Exception {
		BOMItem item = bomManager.findBomItemByOrderAndProdcut(orderId,
				product.getProductId());
		if (item == null) {
			Order order = orderManger.findOrderByOrderId(orderId);
			item = new BOMItem(DataBase.bomItems.size() + 1, orderId,
					product.getProductId(), 0, new BOMItemExtra(), order,
					product, number);
			DataBase.bomItems.add(item);
			items.add(item);
		} else {
			item.setOrderNumber(item.getOrderNumber() + number);
		}
		return item;
	}

	// BOM变采购定单
	public String changeBomToPurchaseOrder() {
		List<BOMItem> bomItems = bomManager.findBomItemsByOrderId(orderId);
		boolean isNeedPurchase = false;
		for (BOMItem item : bomItems) {
			BOMItemExtra extra = item.getExtra();
			if (extra == null || extra.getBomItemExtraId() == 0) {
				setOKInverse();
				errorMessage = "还有BOM尚未填写采购数量!";
				return SUCCESS;
			}
			if (!isNeedPurchase && extra.getActualOrderNumber() != 0) {
				isNeedPurchase = true;
			}
		}

		if (!isNeedPurchase) {
			setOKInverse();
			errorMessage = "BOM中没有原料需要采购";
			return SUCCESS;
		}

		for (PurchaseOrder purchaseOrder : DataBase.purchaseOrders) {
			for (PurchaseOrderItem bomItem : purchaseOrder.getItems()) {
				if (bomItem.getBomItem().getOrderId() == orderId) {
					setOKInverse();
					errorMessage = "已生成采购订单，请不要重复生成";
					return SUCCESS;
				}
			}
		}

		// 生成采购单
		List<PurchaseOrderItem> items = new ArrayList<PurchaseOrderItem>(
				bomItems.size());
		PurchaseOrder purchaseOrder = new PurchaseOrder(
				DataBase.purchaseOrders.size() + 1, false,
				System.currentTimeMillis(), "admin", items);
		DataBase.purchaseOrders.add(purchaseOrder);
		for (BOMItem item : bomItems) {
			if (item.getExtra().getActualOrderNumber() == 0)
				continue;
			PurchaseOrderItem poi = new PurchaseOrderItem(
					DataBase.purchaseOrderItems.size() + 1, false,
					item.getBomItemId(), purchaseOrder.getPurchaseOrderId(),
					item, purchaseOrder);
			items.add(poi);
			DataBase.purchaseOrderItems.add(poi);
			
			
			MaterialProduct product = item.getProduct();
			// 修改冻结(必须在修改虚拟库存前)
			if (product.getBlockStock() == product.getVirtualStock()) {
				int beforeBlockStock = product.getBeforeStock();
				product.setBlockStock(beforeBlockStock
						+ item.getExtra().getActualNeedNumber());
			}

			// 修改虚拟库存
			product.setVirtualStock(product.getVirtualStock()
					+ item.getExtra().getActualOrderNumber());
		}
		setOK();
		return SUCCESS;
	}

	// 分页查询 采购订单
	public String findPurchaseOrderByPage() {
		purchaseOrders = new ArrayList<PurchaseOrder>();
		for (PurchaseOrder order : DataBase.purchaseOrders) {
			if (!order.getIsStorage()) {
				purchaseOrders.add(order);
			}
		}
		totalCount = purchaseOrders.size();
		setOK();
		return SUCCESS;
	}

	// 查询采购定单详情
	public String findPurchaseOrderItemsByPurchaseOrdeId() {
		purchaseOrderItems = new ArrayList<PurchaseOrderItem>();
		for (PurchaseOrderItem item : DataBase.purchaseOrderItems) {
			if (item.getPurchaseOrderId() == purchaseOrderId) {
				purchaseOrderItems.add(item);
			}
		}
		setOK();
		return SUCCESS;
	}

	// 采购订单item入库
	// TODO 修改虚拟库存
	public String makePurchaseOrderItemStorage() {
		for (PurchaseOrderItem item : DataBase.purchaseOrderItems) {
			if (item.getPurchaseOrderId() == purchaseOrderItemId) {
				item.setIsStorage(true);
			}
		}
		setOK();
		return SUCCESS;
	}

	// 采购订单入库
	public String makePurchaseOrderStorage() {
		for (PurchaseOrder order : DataBase.purchaseOrders) {
			if (order.getPurchaseOrderId() == purchaseOrderId) {
				order.setIsStorage(true);
				for (PurchaseOrderItem item : order.getItems()) {
					item.setIsStorage(true);
					// 修改实际库存
					MaterialProduct product = item.getBomItem().getProduct();
					product.setActualStock(product.getActualStock()
							+ item.getBomItem().getExtra()
									.getActualOrderNumber());
				}
				// 使订单可以领料
				order.getItems().get(0).getBomItem().getOrder()
						.setIsGetMaterial(true);

			}
		}
		setOK();
		return SUCCESS;
	}

	public String addBOMItemExtra() {
		double cons = extra.getAmount();
		double wastage = extra.getLoss();
		if (cons < 1) {
			setOKInverse();
			errorMessage = "cons 必须大于1";
			return SUCCESS;
		}
		BOMItem item = bomManager.findBomItemById(bomId);
		int acualNeedNumber = (int) (item.getOrderNumber() * cons * (1 + wastage / 100));
		extra.setActualNeedNumber(acualNeedNumber);
		String mMessage = validateOrderNumber(extra, item);
		if (mMessage != null) {
			setOKInverse();
			errorMessage = mMessage;
			return SUCCESS;
		}
		DataBase.extras.add(extra);
		extra.setBomItemExtraId(DataBase.extras.size());
		extra.setCreateTime(System.currentTimeMillis());
		item.setExtra(extra);

		// 冻结库存(若冻结库存>实际虚拟库存,则取实际虚拟库存，等待下单在修改)
		MaterialProduct product = item.getProduct();
		// 临时保存上次库存
		item.getProduct().setBeforeStock(product.getBlockStock());
		item.getProduct().setBlockStock(
				Math.min(product.getBlockStock() + extra.getActualNeedNumber(),
						product.getVirtualStock()));

		// order是否可以领料了
		canGetMaterial = true;
		List<BOMItem> list = bomManager
				.findBomItemsByOrderId(item.getOrderId());
		for (BOMItem mItem : list) {
			canGetMaterial &= (mItem.getExtra() != null
					&& mItem.getExtra().getBomItemExtraId() != 0 && mItem
					.getExtra().getActualOrderNumber() == 0);
		}
		if (canGetMaterial) {
			Order order;
			try {
				order = orderManger.findOrderByOrderId(item.getOrderId());
				order.setIsGetMaterial(true);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		setOK();
		return SUCCESS;
	}

	// 推荐订单量
	public String findRecommendOrderNumber() {
		double cons = extra.getAmount();
		double wastage = extra.getLoss();
		if (cons < 1) {
			setOKInverse();
			errorMessage = "cons 必须大于1";
			return SUCCESS;
		}
		BOMItem item = bomManager.findBomItemById(bomId);
		int acualNeedNumber = (int) (item.getOrderNumber() * cons * (1 + wastage / 100));
		int virtualNumber = item.getProduct().getVirtualStock();
		int ironNumber = item.getProduct().getProductIronStock();
		int mpqqNumber = item.getProduct().getProductMpqq();
		int blockNumber = item.getProduct().getBlockStock();
		int canUserVirtualNumber = virtualNumber - blockNumber;
		if (canUserVirtualNumber - ironNumber - acualNeedNumber > 0) {
			recommendOrderNumber = 0;
			setOK();
			return SUCCESS;
		}
		recommendOrderNumber = Math.max(mpqqNumber, acualNeedNumber
				+ ironNumber - canUserVirtualNumber);
		setOK();
		return SUCCESS;
	}

	// 验证实际订单量
	private String validateOrderNumber(BOMItemExtra extra, BOMItem item) {
		String msg = null;
		int virtualNumber = item.getProduct().getVirtualStock();
		int actualOrderNumber = extra.getActualOrderNumber();
		int ironNumber = item.getProduct().getProductIronStock();
		int mpqqNumber = item.getProduct().getProductMpqq();
		int actualNeedNumber = extra.getActualNeedNumber();
		int blockNumber = item.getProduct().getBlockStock();
		int canUserVirtualNumber = virtualNumber - blockNumber;

		if (actualOrderNumber != 0 && actualOrderNumber < mpqqNumber) {
			msg = "下单量(" + actualOrderNumber + ")   > " + "MPQQ(" + mpqqNumber
					+ ")??";
		} else if (actualOrderNumber != 0
				&& canUserVirtualNumber + actualOrderNumber - actualNeedNumber
						- ironNumber < 0) {
			msg = "可用虚拟库存(" + canUserVirtualNumber + ")+下单量("
					+ actualOrderNumber + ")    >    实际需求量(" + actualNeedNumber
					+ ")+安全库存(" + ironNumber + ")??";
		}
		return msg;
	}

	// 领取原料
	public String fetchMaterialByOrderId() {
		try {
			Order order = orderManger.findOrderByOrderId(orderId);
			order.setIsFinished(true);

			// 修改库存
			List<BOMItem> items = bomManager.findBomItemsByOrderId(order
					.getOrderId());
			for (BOMItem item : items) {
				MaterialProduct product = item.getProduct();
				product.setActualStock(product.getActualStock()
						- item.getExtra().getActualNeedNumber());
				product.setVirtualStock(product.getVirtualStock()
						- item.getExtra().getActualNeedNumber());
				product.setBlockStock(product.getBlockStock()
						- item.getExtra().getActualNeedNumber());
			}
		} catch (Exception e) {
			e.printStackTrace();
			setError();
			return ERROR;
		}
		setOK();
		return SUCCESS;
	}

	public long getOrderId() {
		return orderId;
	}

	public void setOrderId(long orderId) {
		this.orderId = orderId;
	}

	public OrderItem getItem() {
		return item;
	}

	public void setItem(OrderItem item) {
		this.item = item;
	}

	public List<Order> getOrders() {
		return orders;
	}

	public void setOrders(List<Order> orders) {
		this.orders = orders;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public boolean isSuccess() {
		return success;
	}

	public void setSuccess(boolean success) {
		this.success = success;
	}

	public int getTotalCount() {
		return totalCount;
	}

	public void setTotalCount(int totalCount) {
		this.totalCount = totalCount;
	}

	public List<BOMItem> getBomItems() {
		return bomItems;
	}

	public void setBomItems(List<BOMItem> bomItems) {
		this.bomItems = bomItems;
	}

	public List<OrderItem> getOrderItems() {
		return orderItems;
	}

	public void setOrderItems(List<OrderItem> orderItems) {
		this.orderItems = orderItems;
	}

	public long getBomId() {
		return bomId;
	}

	public void setBomId(long bomId) {
		this.bomId = bomId;
	}

	public BOMItem getBomItem() {
		return bomItem;
	}

	public void setBomItem(BOMItem bomItem) {
		this.bomItem = bomItem;
	}

	public BOMItemExtra getExtra() {
		return extra;
	}

	public void setExtra(BOMItemExtra extra) {
		this.extra = extra;
	}

	public List<PurchaseOrder> getPurchaseOrders() {
		return purchaseOrders;
	}

	public void setPurchaseOrders(List<PurchaseOrder> purchaseOrders) {
		this.purchaseOrders = purchaseOrders;
	}

	public long getPurchaseOrderId() {
		return purchaseOrderId;
	}

	public void setPurchaseOrderId(long purchaseOrderId) {
		this.purchaseOrderId = purchaseOrderId;
	}

	public List<PurchaseOrderItem> getPurchaseOrderItems() {
		return purchaseOrderItems;
	}

	public void setPurchaseOrderItems(List<PurchaseOrderItem> purchaseOrderItems) {
		this.purchaseOrderItems = purchaseOrderItems;
	}

	public long getPurchaseOrderItemId() {
		return purchaseOrderItemId;
	}

	public void setPurchaseOrderItemId(long purchaseOrderItemId) {
		this.purchaseOrderItemId = purchaseOrderItemId;
	}

	public String getErrorMessage() {
		return errorMessage;
	}

	public void setErrorMessage(String errorMessage) {
		this.errorMessage = errorMessage;
	}

	public int getRecommendOrderNumber() {
		return recommendOrderNumber;
	}

	public void setRecommendOrderNumber(int recommendOrderNumber) {
		this.recommendOrderNumber = recommendOrderNumber;
	}

	public boolean getCanGetMaterial() {
		return canGetMaterial;
	}

	public void setCanGetMaterial(boolean canGetMaterial) {
		this.canGetMaterial = canGetMaterial;
	}

}
